package com.helpustotravel.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helpustotravel.core.ServletBase;
import com.helpustotravel.model.dao.HelpDAO;
import com.helpustotravel.model.dao.PositionDAO;
import com.helpustotravel.model.dao.TravellerDAO;
import com.helpustotravel.model.jdo.Help;
import com.helpustotravel.model.jdo.Position;
import com.helpustotravel.model.jdo.Traveller;

@SuppressWarnings("serial")
public class AddPositionServlet extends ServletBase {

	public static String NAME = "AddPosition";
	
	protected HttpServletResponse doTache(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		String name = req.getParameter("name");
		String adresse = req.getParameter("adresse");
		double x = Double.parseDouble(req.getParameter("x"));
		double y = Double.parseDouble(req.getParameter("y"));
		double adresseX = Double.parseDouble(req.getParameter("adressex"));
		double adresseY = Double.parseDouble(req.getParameter("adressey"));
		int level = Integer.parseInt(req.getParameter("level"));
		String localisation = req.getParameter("localisation");
		String search = req.getParameter("search");
		
		if(x == 0 || y == 0) {
			resp.getWriter().println("x ou y nul");
			return resp;
		}
		
		TravellerDAO travellerDao = new TravellerDAO(pm);
		Traveller traveller = travellerDao.getTraveller(name);
		
		List<Long> listPositions = traveller.getPositionIds();
		long positionId = listPositions.get(listPositions.size() - 1) + 1;
		traveller.addPosition(positionId);
		travellerDao.addTraveller(traveller);
		
		Position position = new Position();
		position.setId(positionId);
		position.setDate(new Date());
		position.setAdresse(adresse);
		position.setX(x);
		position.setY(y);
		position.setAdresseX(adresseX);
		position.setAdresseY(adresseY);
		position.setLevel(level);
		position.setTravellerName(name);
		
		PositionDAO positionDao = new PositionDAO(pm);
		positionDao.addPosition(position);
		
		Help help = new Help();
		help.setDate(new Date());
		help.setIp(this.adresseIp);
		help.setTravellerName(name);
		help.setPositionId(positionId);
		help.setLocalisation(localisation);
		help.setSearch(search);
		help.generateSession();
		
		HelpDAO helpDao = new HelpDAO(pm);
		helpDao.addHelp(help);
		
		resp.getWriter().println("ok," + help.getSession());
		
		return resp;
	}
}
